import fs from 'fs'
import path from 'path'
import stream from 'stream'
// import fetch, { RequestInfo, RequestInit, Response } from 'node-fetch'
import env from './env'

// 调用接口获取数据
const request: (url: RequestInfo, init?: RequestInit) => Promise<Response> = async (url, init) => {
  const response = await fetch(url, init)
  if (response.ok) return response
  throw Error(`Unexpected response: ${response.statusText}`)
}

export default async (url: RequestInfo): Promise<string> => {
  const response = await request(url)
  if (response.body == null) throw Error('Unexpected response: Response body is empty')
  // 创建临时文件
  await fs.promises.mkdir(env.temp, { recursive: true })

  // 拼接文件名
  const filePath = path.join(env.temp, Date.now().toString() + '.zip')

  // 将下载的文件写入临时文件
  await stream.promises.pipeline(response.body, fs.createWriteStream(filePath))

  // 返回临时文件路径
  return filePath
}
